# @ModuleName: db_handle
# @Author: zxl
# @Time: 2024/6/17 16:36'

import pymysql

class DbHandle:
    def __init__(self,host = 'localhost',port = 3306,user = 'root',password = 'Sy20010910',database = 'quote'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.charset = 'utf8'
        self.port = port
        self.cursorclass = pymysql.cursors.DictCursor
        self.conn = None

    def get_connection(self):
        if not self.conn or not self.conn.open:  # 检查连接是否已存在且是打开的
            self.conn = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database,
                charset=self.charset)
        return self.conn

    def search_query(self,query,params = None):
        conn = self.get_connection()
        with conn.cursor(self.cursorclass) as cursor:
            if params :
                cursor.execute(query,params)
            else:
                cursor.execute(query)
            # print(query)
            results = cursor.fetchall()
        return results

    def update_query(self,query,params = None):
        conn = self.get_connection()
        with conn.cursor(self.cursorclass) as cursor:
            if params :
                res = cursor.execute(query, params)
            else:
                res = cursor.execute(query)
            conn.commit()
        return res

    def close_connection(self):
        if self.conn and self.conn.open:
            self.conn.close()


